import React, { useState } from "react";
import { Document, Page, pdfjs } from "react-pdf";

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

const PDFPreview: React.FC = () => {
  const [numPages, setNumPages] = useState<number | null>(null);
  const [pageNumber, setPageNumber] = useState(1);
  const [error, setError] = useState<string | null>(null);

  const onDocumentLoadSuccess = ({ numPages }: { numPages: number }) => {
    setNumPages(numPages);
    setPageNumber(1);
    setError(null);
  };

  const onDocumentLoadError = (error: Error) => {
    setError("加载失败");
    console.log("error", error);
  };

  const nextPage = () => {
    setPageNumber((prev) => Math.min(prev + 1, numPages || 1));
  };

  const prevPage = () => {
    setPageNumber((prev) => Math.max(prev - 1, 1));
  };

  const pdfURL =
    "https://car-dev-1314896495.cos.ap-nanjing.myqcloud.com/files/2023-08-01/78404381984646a19a9510df6cad701c-%E5%90%88%E5%90%8C%E7%B3%BB%E7%BB%9F%E6%93%8D%E4%BD%9C%E6%89%8B%E5%86%8C.pdf";

  return (
    <div>
      {error ? (
        <p>{error}</p>
      ) : (
        <div>
          <div>
            <button
              type="button"
              onClick={prevPage}
              disabled={pageNumber === 1}
            >
              上一页
            </button>
            <button
              type="button"
              onClick={nextPage}
              disabled={pageNumber === numPages}
            >
              下一页
            </button>
          </div>

          <div>
            <Document
              file={pdfURL}
              onLoadSuccess={onDocumentLoadSuccess}
              onLoadError={onDocumentLoadError}
            >
              <Page pageNumber={pageNumber} />
            </Document>
          </div>

          <p>
            Page {pageNumber} of {numPages || "--"}
          </p>
        </div>
      )}
    </div>
  );
};

export default PDFPreview;
